from collections import deque
from game.gui.label import MultiLabel

class MessageManager:
    def __init__(self, rect):
        self.max_msg = 20
        self.max_show = 7
        self.sep = "<br>"
        self.msg_queue = deque()
        self.widget = MultiLabel(rect=rect)
        self.current_str = None

    def add_msg(self, msg):
        if self.current_str is None:
            self.current_str = msg
        else:
            self.current_str += msg

    def rebuild(self):
        if self.current_str is not None:
            self.msg_queue.append(self.current_str)
            if len(self.msg_queue) > self.max_msg:
                self.msg_queue.popleft()
            self.current_str = None

        msg_last = len(self.msg_queue)
        msg_first = msg_last - self.max_show
        if msg_last < self.max_show:
            msg_first = 0

        data = self.sep.join([self.msg_queue[line] for line in xrange(msg_first, msg_last)])
        self.widget.set_text(data)